Thread: Error: expected identifier or ‘(’ before ‘{’ token

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    30

    Error: expected identifier or ‘(’ before ‘{’ token

    Hi. I'm new to programming. I'm making a school work, and I need some help, because I get the errors:

    Code:
    main.c:23: error: expected identifier or ‘(’ before ‘{’ token
    main.c:28: error: expected identifier or ‘(’ before ‘{’ token
    And I don't know how to fix. I searched a lot, but nothing came up. And finally... My code. Pretty simple.

    Code:
    //Este programa foi feito por X.
    //Notas:
    //O comando printf introduz texto para o ecrã. O "\n" significa introduzir numa nova linha.
    //Já pus o título. Seguir o seu exemplo. Meter o resto por baixo. Não mexer nas outras coisas.
    //Have fun!
    //P.S.
    //O texto que começa com "//" são comentários. Não são interpretados pelo compilador, e não aparecem no programa em si.
    
    #include <stdio.h>
    #include <allegro.h>
    
    int main()
    
    {
    BITMAP *Buffer; 
    PALETTE *Pal; 
    allegro_init(); 
    set_color_depth(24);
    set_gfx_mode(GFX_AUTODETECT, 800, 600, 0, 0); 
    	install_keyboard();
    }
    
    {
    Buffer = load_bitmap("PC.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    
    {
      printf( "Linguagem Binária\n" );
      printf("Trabalho realizado por:\n");
      printf("Neste trabalho vou tratar sobre a linguagem binária, falar sobre a sua história, como é constituída, os vários tipos de coisas que existem...\n");
    	printf("Os computadores nasceram em 4000 a.C. Na verdade, não era bem um computador. Mas era o iníco de uma nova era.\n");
    	printf("Este aparelho era muito simples, e chamava-se ÁBACO.\n");
    	printf("Este computador mecânico foi criado por Charles Babbage.\n");
    	printf("Mas não estamos aqui para falar de ábacos tão antigos, pois não? Por isso vamos continuar.");
    	printf("Começemos pela definição de um computador. Um computador é uma máquina capaz de de tratar e processar dados automáticamente.\n");
    	printf("Um computador tanto pode ser um ábaco (como vimos anteriormente), uma calculadora, um computador analógico ou um computador digital.\n");
    	printf("Os computadores pessoais e os portáteis estão associados à Era da Informação (ou à Internet).\n");
    	printf("Os computadores evoluiram de tal forma que chegam a ser pequenos dispositivos muito capazes, ou grandes monstros!\n");
    	{
    Buffer = load_bitmap("Super.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	{
    Buffer = load_bitmap("PDA.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	printf("O computador é constituído por:\n");
    	{
    Buffer = load_bitmap("consti.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	printf("O SISTEMA OPERATIVO\n");
    	printf("...\n");
    	printf("O Sistema Operativo é a ponte entre o hardware e os programas. Gerencia a memória, o disco, os periféricos...\n");
    	printf("Fornece uma interface entre o computador e o utilizador.\n");
    	{
    Buffer = load_bitmap("SO.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	printf("Existem vários tipos de SOs (ou OS, no Inglês).\n");
    	printf("Cada um oferece funcionalidades diferentes. Uns oferecem mais visual, outros mais performance... \n");
    	printf("...\n");
    	printf("Exemplos:\n");
    	printf("...\n");
    	printf("Windows\n");
    	printf("Mac\n");
    	printf("Linux\n");
    	printf("Unix\n");
    	printf("Solaris\n");
    	printf("E muitos, muitos outros...\n");
    	printf("...\n");
    	printf("Como podem ver no gráfico acima, o Windows é o mais utilizado. Mas não quer dizer que seja o melhor. É apenas o mais popular, devido a ser de fácil utilização.\n");
    	printf("O Mac aposta no visual. Mais uma vez, não quer dizer que seja o melhor.\n");
    	printf("No Linux e nos outros, temos um SO que aposta na performance, estabilidade, e através de pequenos aditivos, no visual. O único mal que tem é não ser tão acessível a nível de aprendizagem, porque a nível económico... Bem, é grátis.\n");
    	{
    Buffer = load_bitmap("Ubuntu.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	{
    Buffer = load_bitmap("XP.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	{
    Buffer = load_bitmap("7.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	printf("...\n");
    	printf("A INTERFACE\n");
    	printf("...\n");
    	printf("Existem dois tipos de interface: A gráfica e a linha de comandos.\n");
    	{
    Buffer = load_bitmap("command.bmp", Pal); 
    	draw_sprite(screen, Buffer, 0, 0); 
    }
    	printf("À interface gráfica chama-se GUI (do Inglês Grapical User Interface).\n");
    	printf("Aqui podemos explorar um computador com um teclado e um rato, e explora-se facilmente...\n");
    	printf("No Windows Vista e 7 temos o Aero, nos outros Windows o ambiente gráfico padrão.\n");
    	printf("No Linux, temos vários, como o Gnome, o KDE, BlackBox, XFCE, entre outros...\n");
    	printf("Também temos o Compiz, para melhorar o computador visualente, com efeitos como o cubo, janelas gelatinosas...\n");
    	printf("...\n");
    	printf("Na linha de comandos, apenas vemos um texto simples, num fundo preto. É o clássico.\n");
    	printf("Temos vários SOs de linha de comandos, com o MSDOS, o FreeDOS...\n");
    	printf("É essencialmente utilizado por programadores, e além de ser único no SO, também pode ser um complemento, como o cmd no Windows ou a consola/terminal no Linux/Unix.\n");
    	printf("...\n");
    	printf("E esta pequena história da linguagem binária acabou. Espero que tenham gostado.\n");
    	printf("XXXX, Xº XX, XºX.\n");
    	printf("...\n");
    	printf("FIM\n");
    	getchar();
      return 0;
    }
    And when I try to put a ";" in front of "}" I get this error:

    Code:
    main.c:112: warning: ISO C does not allow extra ‘;’ outside of a function
    Can you help me?

    Regards,

    JPCanaverde

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Simple. You've got code defined outside of a function. Put that inside main(), get rid of all of those superfulous brackets (not required to compile, but nonetheless unnecessary), and you should be good to go...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Also indent your code properly to avoid such errors in the future and make sure you change:

    int main() to int main(void). Read the FAQ for more details.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    30
    Ok, so now instead of int main() is int main(void). But I still can't figure out how I put the code inside main()...

    Can you explain to do what I have to do? Sorry, still learning.

  5. #5
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by jpcanaverde View Post
    Ok, so now instead of int main() is int main(void). But I still can't figure out how I put the code inside main()...

    Can you explain to do what I have to do? Sorry, still learning.
    Code:
    int main( void )
    {
        // your code goes here
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    30
    I'm not understanding.

    I put:

    Code:
    int main( void ) 
    {
    BITMAP *Buffer; 
    PALETTE *Pal; 
    allegro_init(); 
    set_color_depth(24);
    set_gfx_mode(GFX_AUTODETECT, 800, 600, 0, 0); 
    	install_keyboard();
    }
    And I compile again... And it gives me the same error. Am I missing something? What code do I have to put inside main? Sorry again... And thank's for your patience.

  7. #7
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Your problem is that you are not indenting your code correctly and are using extra {} blocks which are completely useless and only add to the lack of readability of the code. If the compiler complains about a bracket, then you have a bracket problem. If every if/else, every function, and every loop would have a clear system of brackets like so:

    Code:
    int main(void){
    
      if(something){
    
      }else{
    
      }
       return 0;
    }
    you would be able to spot the problem immediately.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  8. #8
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Your problem is that you went crazy with the curly braces, no idea why but because of that the compiler thinks that main() ended with the first close brace '}' and everything after that it doesn't know what to do with...I will try to clean it up a little but you really truly need to learn more about the language, even if it means looking at code others have written...
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    30
    Made an expericence and removed some brackets... But it gave me tons of errors. What brackets do I have to remove?

  10. #10
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by jpcanaverde View Post
    Made an expericence and removed some brackets... But it gave me tons of errors. What brackets do I have to remove?
    You have one function int main() no if/elses no loops. WHY DO YOU HAVE MORE THAN TWO BRACKETS?
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by jpcanaverde View Post
    I'm not understanding.

    I put:

    Code:
    int main( void ) 
    {
    BITMAP *Buffer; 
    PALETTE *Pal; 
    allegro_init(); 
    set_color_depth(24);
    set_gfx_mode(GFX_AUTODETECT, 800, 600, 0, 0); 
        install_keyboard();
    }
    And I compile again... And it gives me the same error. Am I missing something? What code do I have to put inside main? Sorry again... And thank's for your patience.
    Well, that should compile (barring "include" issues). What error are you getting with the above code?

    Anyway, consider this code:

    Code:
    int main( void )
    {
    
    }
    {
        int j = 0;
    }
    That won't compile because the scope of 'j' simply can't exist outside of a function. Relocating the code as so:

    Code:
    int main( void )
    {
        {
            int j = 0;
        }
    }
    That works fine, but now we have unnecessarily enclosed a declaration in an anonymous scope (again, harmless, but pointless). So really all we need is:

    Code:
    int main( void )
    {
        int j = 0;
    }
    Does that make sense?
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  12. #12
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    All I did was properly reformat the code and got rid of the superfluous braces and it compiles now with errors simple relating to the fact that I do not have the Allegro library installed (so it knows nothing of the data types and functions) but as I am in the final stages of an OS upgrade as I write this, I am NOT going to install it just to prove it works. On the other hand, even if I had it installed, I do not speak the language in the printf()s and do not have the patience to run each line through Google to translate to be sure the program works as advertised which is getting way beyond simple compile errors. One last warning before I post:

    It *could* have been the case that the OP didn't lose his or her mind with the braces but rather was taking a stab (albeit failed on) at putting these things into functions and just left out the function signatures...and function calls..and...ok nevermind that was a dumb assumption.

    Without further ado...this is what we were trying to get the OP to do...she/he really needs to read a C book though.
    Code:
    //Este programa foi feito por X.
    //Notas:
    //O comando printf introduz texto para o ecrã. O "\n" significa introduzir numa nova linha.
    //Já pus o título. Seguir o seu exemplo. Meter o resto por baixo. Não mexer nas outras coisas.
    //Have fun!
    //P.S.
    //O texto que começa com "//" são comentários. Não são interpretados pelo compilador, e não aparecem no programa em si.
    
    #include <stdio.h>
    #include <allegro.h>
    
    int main()
    
    {
       BITMAP *Buffer; 
       PALETTE *Pal; 
       allegro_init(); 
       set_color_depth(24);
       set_gfx_mode(GFX_AUTODETECT, 800, 600, 0, 0); 
       install_keyboard();
    
    
    
       Buffer = load_bitmap("PC.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
    
    
       printf( "Linguagem Binária\n" );
       printf("Trabalho realizado por:\n");
       printf("Neste trabalho vou tratar sobre a linguagem binária, falar sobre a sua história, como é constituída, os vários tipos de coisas que existem...\n");
       printf("Os computadores nasceram em 4000 a.C. Na verdade, não era bem um computador. Mas era o iníco de uma nova era.\n");
       printf("Este aparelho era muito simples, e chamava-se ÁBACO.\n");
       printf("Este computador mecânico foi criado por Charles Babbage.\n");
       printf("Mas não estamos aqui para falar de ábacos tão antigos, pois não? Por isso vamos continuar.");
       printf("Começemos pela definição de um computador. Um computador é uma máquina capaz de de tratar e processar dados automáticamente.\n");
       printf("Um computador tanto pode ser um ábaco (como vimos anteriormente), uma calculadora, um computador analógico ou um computador digital.\n");
       printf("Os computadores pessoais e os portáteis estão associados à Era da Informação (ou à Internet).\n");
       printf("Os computadores evoluiram de tal forma que chegam a ser pequenos dispositivos muito capazes, ou grandes monstros!\n");
    	
       Buffer = load_bitmap("Super.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
    	
       Buffer = load_bitmap("PDA.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
       printf("O computador é constituído por:\n");
    	
       Buffer = load_bitmap("consti.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
       printf("O SISTEMA OPERATIVO\n");
       printf("...\n");
       printf("O Sistema Operativo é a ponte entre o hardware e os programas. Gerencia a memória, o disco, os periféricos...\n");
       printf("Fornece uma interface entre o computador e o utilizador.\n");
    	
       Buffer = load_bitmap("SO.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
       printf("Existem vários tipos de SOs (ou OS, no Inglês).\n");
       printf("Cada um oferece funcionalidades diferentes. Uns oferecem mais visual, outros mais performance... \n");
       printf("...\n");
       printf("Exemplos:\n");
       printf("...\n");
       printf("Windows\n");
       printf("Mac\n");
       printf("Linux\n");
       printf("Unix\n");
       printf("Solaris\n");
       printf("E muitos, muitos outros...\n");
       printf("...\n");
       printf("Como podem ver no gráfico acima, o Windows é o mais utilizado. Mas não quer dizer que seja o melhor. É apenas o mais popular, devido a ser de fácil utilização.\n");
       printf("O Mac aposta no visual. Mais uma vez, não quer dizer que seja o melhor.\n");
       printf("No Linux e nos outros, temos um SO que aposta na performance, estabilidade, e através de pequenos aditivos, no visual. O único mal que tem é não ser tão acessível a nível de aprendizagem, porque a nível económico... Bem, é grátis.\n");
    	
       Buffer = load_bitmap("Ubuntu.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
    	
       Buffer = load_bitmap("XP.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
    	
       Buffer = load_bitmap("7.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
       printf("...\n");
       printf("A INTERFACE\n");
       printf("...\n");
       printf("Existem dois tipos de interface: A gráfica e a linha de comandos.\n");
    	
       Buffer = load_bitmap("command.bmp", Pal); 
       draw_sprite(screen, Buffer, 0, 0); 
    
       printf("À interface gráfica chama-se GUI (do Inglês Grapical User Interface).\n");
       printf("Aqui podemos explorar um computador com um teclado e um rato, e explora-se facilmente...\n");
       printf("No Windows Vista e 7 temos o Aero, nos outros Windows o ambiente gráfico padrão.\n");
       printf("No Linux, temos vários, como o Gnome, o KDE, BlackBox, XFCE, entre outros...\n");
       printf("Também temos o Compiz, para melhorar o computador visualente, com efeitos como o cubo, janelas gelatinosas...\n");
       printf("...\n");
       printf("Na linha de comandos, apenas vemos um texto simples, num fundo preto. É o clássico.\n");
       printf("Temos vários SOs de linha de comandos, com o MSDOS, o FreeDOS...\n");
       printf("É essencialmente utilizado por programadores, e além de ser único no SO, também pode ser um complemento, como o cmd no Windows ou a consola/terminal no Linux/Unix.\n");
       printf("...\n");
       printf("E esta pequena história da linguagem binária acabou. Espero que tenham gostado.\n");
       printf("XXXX, Xº XX, XºX.\n");
       printf("...\n");
       printf("FIM\n");
       getchar();
       return 0;
    }
    PS: you may want to break up those long printf()s a bit, say 80 char max per line. Just sayin.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  13. #13
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Wow, nice work Jeff.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  14. #14
    Registered User
    Join Date
    May 2010
    Posts
    30
    Another error:

    Code:
    main.c: In function ‘main’:
    main.c:24: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:41: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:45: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:50: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:58: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:77: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:81: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:85: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    main.c:93: warning: passing argument 2 of ‘load_bitmap’ from incompatible pointer type
    /usr/include/allegro/datafile.h:91: note: expected ‘struct RGB *’ but argument is of type ‘struct RGB (*)[256]’
    >Exit code: 0
    Weird... And thank's jeff!

  15. #15
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Let me guess: you have an array of structs and decided, against all logic, to put & before the array name when passing to the function?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. Connecting to a mysql server and querying problem
    By Diod in forum C++ Programming
    Replies: 8
    Last Post: 02-13-2006, 10:33 AM
  3. Why wont my function exit correctly?
    By LightsOut06 in forum C Programming
    Replies: 2
    Last Post: 10-09-2005, 09:23 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM

Tags for this Thread